<template>
    <div class="zy-content">
      <div class="searchBox search-box-layout">
        <Row :gutter="24">
          <Col span="4">
            <div>
              <p class="label">{{$t('common.Type')}}</p>
              <div class="ipt">
                <Select
                    v-model="typeInfo"
                    filterable
                    :placeholder="`${$t('common.selectInfo')}`"
                    @on-change="typeChange"
                >
                  <Option v-for="item in typeList"
                          :value="item.value"
                          :label="item.label"
                          :key="item.value"/>
                </Select>
              </div>
            </div>
          </Col>
          <Col span="4">
            <div>
              <p class="label">{{$t('common.PartNo')}}</p>
              <div class="ipt">
                <Input v-model="searchParams.value" :placeholder="`${$t('common.inputInfo')}`"/>
              </div>
            </div>
          </Col>
          <Col span="4">
            <div>
              <p class="label">{{$t('common.SpareNumber')}}</p>
              <div class="ipt">
                <Input v-model="searchParams.backupNo" :placeholder="`${$t('common.inputInfo')}`"/>
              </div>
            </div>
          </Col>
          <Col span="4">
            <div>
              <p class="label">{{$t('common.OriginalWarehouse')}}</p>
              <div class="ipt">
                <Select v-model="searchParams.oldWarehouseId"
                        @on-change="warehouseSelectChange($event,'old')"
                        @on-clear="warehouseClear"
                        ref="warehouseSelect"
                        clearable :placeholder="`${$t('common.selectInfo')}`">
                  <Option v-for="(item,index) of warehouseList"
                          :value="item.id"
                          :key="index">
                    {{ item.backupName }}
                  </Option>
                </Select>
              </div>
            </div>
          </Col>
          <Col span="4">
            <div>
              <p class="label">{{$t('common.OriginalRack')}}</p>
              <div class="ipt">
                <Select v-model="searchParams.oldShelfId"
                        @on-change="shelvesSelectChange($event,'old')"
                        @on-clear="shelvesClear"
                        ref="shelvesSelect"
                        clearable :placeholder="`${$t('common.selectInfo')}`">
                  <Option v-for="(item,index) of shelvesList" :value="item.id" :key="index">
                    {{ item.shelf }}
                  </Option>
                </Select>
              </div>
            </div>
          </Col>
          <Col span="4">
            <div>
              <p class="label">{{$t('common.OriginalLocation')}}</p>
              <div class="ipt">
                <Select v-model="searchParams.oldLocationId"
                        ref="locationSelect"
                        clearable :placeholder="`${$t('common.selectInfo')}`">
                  <Option v-for="(item,index) of locationList" :value="item.id" :key="index">
                    {{ item.location }}
                  </Option>
                </Select>
              </div>
            </div>
          </Col>
          <Col span="4">
            <div>
              <p class="label">{{$t('common.NowWarehouse')}}</p>
              <div class="ipt">
                <Select v-model="searchParams.warehouseId"
                        @on-change="warehouseSelectChange"
                        @on-clear="warehouseClear"
                        ref="warehouseSelect"
                        clearable :placeholder="`${$t('common.selectInfo')}`">
                  <Option v-for="(item,index) of newwarehouseList"
                          :value="item.id"
                          :key="index">
                    {{ item.backupName }}
                  </Option>
                </Select>
              </div>
            </div>
          </Col>
          <Col span="4">
            <div>
              <p class="label">{{$t('common.NowRack')}}</p>
              <div class="ipt">
                <Select v-model="searchParams.shelfId"
                        @on-change="shelvesSelectChange"
                        @on-clear="shelvesClear"
                        ref="shelvesSelect"
                        clearable :placeholder="`${$t('common.selectInfo')}`">
                  <Option v-for="(item,index) of newshelvesList" :value="item.id" :key="index">
                    {{ item.shelf }}
                  </Option>
                </Select>
              </div>
            </div>
          </Col>
          <Col span="4">
            <div>
              <p class="label">{{$t('common.NowLocation')}}</p>
              <div class="ipt">
                <Select v-model="searchParams.locationId"
                        ref="locationSelect"
                        clearable :placeholder="`${$t('common.selectInfo')}`">
                  <Option v-for="(item,index) of newlocationList" :value="item.id" :key="index">
                    {{ item.location }}
                  </Option>
                </Select>
              </div>
            </div>
          </Col>
          <Col span="4">
            <div>
              <p class="label">{{$t('common.ScrapBy')}}</p>
              <div class="ipt">
                <Select v-model="searchParams.scrapName"
                        filterable clearable :placeholder="`${$t('common.selectInfo')}`"
                        :remote-method="getApplicationOAList"
                >
                  <Option v-for="item of OAList"
                          :value="item.id"
                          :key="item.id"
                          :label="item.showName"
                  />
                </Select>
              </div>
            </div>
          </Col>
          <Col span="4">
            <div>
              <p class="label">{{$t('common.ScrapTime')}}</p>
              <div class="ipt">
                <DatePicker
                    v-model="applyTimeList"
                    type="datetimerange"
                    format="yyyy-MM-dd HH:mm:ss"
                    placement="bottom-end"
                    :placeholder="`${$t('common.selectInfo')}`"
                    @on-change="handleRangeChange"
                />
              </div>
            </div>
          </Col>
          <Col span="4">
            <div>
              <p class="label hide-label">--</p>
              <div class="ipt">
                <Button class="search-btn" v-has="'warehousingSearch'" type="primary" @click="changeNum">{{ $t('common.Query') }}</Button>
                <Button v-has="'warehousingSearch'"
                    class="reset-btn"
                    @click="reset()"
                >{{ $t('common.reset') }}
                </Button>
              </div>
            </div>
          </Col>
        </Row>
      </div>
      <div class="list-layout mt16">
        <div class="btns clear">
          <span class="title">{{ $t('common.listInformation') }}</span>
          <Button v-has="'warehousingExport'" @click="handleOutRecords">{{ $t('common.Export') }}</Button>
        </div>
        <div class=" tableContent" style="border: none">
          <div class="tableContent">
            <Table :columns="tableColumns"
                   @on-selection-change="onSelectChange"
                   :data="tablelist">
            </Table>
          </div>

        </div>
        <div class="pageWrap mt16">
          <pageLeftTitle :total="total" :selected="delIds.length" />
          <Page :total="total"
                :page-size="pageSize"
                :page-size-opts="pageSizeOption"
                :current="pageNum"
                @on-change="changePageNum"
                @on-page-size-change="changePageSize"
                show-sizer show-total/>
        </div>
      </div>
    </div>
</template>

<script>
import {
    getCompanyList,
    getBackupsByCompany,
    getShelfByBackupId,
    getLocationByShelfId
} from "@/api/index.js";
import recursion from "@/util/recursion";
import fileDownload from "js-file-download";

export default {
    name: "addScrapApply",
    data() {
        return {
            total: 0,
            typeInfo: "备件报废记录",
            typeList: [
                // {label:'备件领用记录',value:'备件领用记录'},
                // {label:'备件归还记录',value:'备件归还记录'},
                // {label:'备件报废记录',value:'备件报废记录'}
                {label: `${this.$t('common.PickingRecord')}`, value: '备件领用记录'},
                {label: `${this.$t('common.ReturnRecord')}`, value: '备件归还记录'},
                {label: `${this.$t('common.ScrapRecord')}`, value: '备件报废记录'}
            ],
            pageSizeOption: [10, 20, 30],
            materielNoInfo: '',
            materielNoList: [],
            backupNoList: [],
            pageNum: 1,
            pageSize: 10,
            searchParams: {},
            orgList: [],
            companyList: [{id: '', name: '全部'}],
            warehouseList: [],
            shelvesList: [],
            locationList: [],
            idNum: 0,
            companyrowList: [],
            warehouserowList: [],
            shelvesrowList: [],
            locationrowList: [],

            newwarehouseList: [],
            newshelvesList: [],
            newlocationList: [],

            tablelist: [],
            OAList: [],
            materielNoObj: {},
            paramsInfo: {},
            backupNoObj: {},
            tableColumns: [
                {
                    type: 'selection',
                    width: 60,
                    align: 'center',
                },
                {
                    title: `${this.$t('common.ScrapTime')}`,
                    key: 'scrapTime',
                    align: "center",
                    width: 150
                },
                {
                    title: `${this.$t('common.PartNo')}`,
                    align: "center",
                    key: 'materielNo',
                    width: 130
                },
                {
                    title: `${this.$t('common.SpareNumber')}`,
                    align: "center",
                    key: 'backupNo',
                    width: 140
                },
                {
                    title: `${this.$t('common.GoodsName')}`,
                    align: "center",
                    key: 'goodsName',
                    width: 140
                },
                {
                    title: `${this.$t('common.Specification')}`,
                    align: "center",
                    key: 'specification',
                    width: 140
                },
                {
                    title: `${this.$t('common.OriginalWarehouse')}`,
                    align: "center",
                    key: 'oldWarehouseName',
                    width: 160
                },
                {
                    title: `${this.$t('common.OriginalRack')}`,
                    align: "center",
                    key: 'oldShelfName',
                    width: 140
                },
                {
                    title: `${this.$t('common.OriginalLocation')}`,
                    align: "center",
                    key: 'oldLocationName',
                    width: 140
                },
                {
                    title: `${this.$t('common.NowWarehouse')}`,
                    align: "center",
                    key: 'newWarehouseName',
                    width: 140
                },
                {
                    title: `${this.$t('common.NowRack')}`,
                    align: "center",
                    key: 'newShelfName',
                    width: 120
                },
                {
                    title: `${this.$t('common.NowLocation')}`,
                    align: "center",
                    key: 'newLocationName',
                    width: 150
                },
                {
                    title: `${this.$t('common.ScrapQuantity')}`,
                    align: "center",
                    key: 'scrapNum',
                    width: 140
                },
                {
                    title: `${this.$t('common.ScrapReason')}`,
                    align: "center",
                    key: 'scrapRemark',
                    width: 160
                },
                {
                    title: `${this.$t('common.ControlMode')}`,
                    align: "center",
                    key: 'manageTypeName',
                    width: 120
                },
                {
                    //title: '备件ABC分类',
                    title: `${this.$t('spareParts.SparePartABC')}`,
                    align: "center",
                    key: 'abcType',
                    width: 160
                },
                {
                    //title: '资产类型',
                    title: `${this.$t('spareParts.AssetType')}`,
                    align: "center",
                    key: 'assetTypeName',
                    width: 160
                },
                {
                    //title: '物品分类',
                    title: `${this.$t('spareParts.ObjectClassification')}`,
                    align: "center",
                    key: 'goodsTypeName',
                    width: 120
                },
                {
                    // title: '采购价格',
                    title: `${this.$t('spareParts.PurchasePrice')}`,
                    align: "center",
                    key: 'price',
                    width: 140
                },
                {
                    // title: '报废人',
                    title: `${this.$t('common.ScrapBy')}`,
                    align: "center",
                    key: 'scrapName',
                    width: 140
                },
                {
                    // title: '安装时间',
                    title: `${this.$t('common.InstallationTime')}`,
                    align: "center",
                    key: 'installTime',
                    width: 160
                },
                {
                    // title: '更换时间',
                    title: `${this.$t('common.ChangeTime')}`,
                    align: "center",
                    key: 'updateTime',
                    width: 160
                }
            ],
            applyTimeList: [],
            selectTable: [],
            delIds: []
        }
    },
    created() {
        this.companySelectChange(7)
        this.getOrgList()
        this.searchList()
    },
    methods: {
        reset(){
            this.searchParams = {};
            this.applyTimeList = []
            this.searchList()
        },
        onSelectChange(val) {
            this.selectTable = val
            let myArray = [];
            val.map((item) => {
                myArray.push(item.id);
            });
            this.delIds = myArray;
        },
        handleOutRecords() {
            let params = {
                pageNum: this.pageNum,
                pageSize: this.pageSize,
                delIds: this.delIds,
                ...this.searchParams
            }
            const filName = '备件报废记录'
            this.axios({
                method: 'post',
                url: '/dms/dmsBackupApplyRecord/exportDmsBackupScrapRecord',
                responseType: 'blob',
                data: params
            }).then(res => {
                fileDownload(res, filName + '.xlsx')
            })
            // if (!this.selectTable.length){
            //   this.$Message.error('请勾选')
            //   return
            // }
            // let data = {
            //   pageNum: this.pageNum,
            //   pageSize: this.pageSize,
            //   ...this.searchParams
            // }
            // const filName = '备件报废记录'
            // this.axios({
            //   method: 'post',
            //   url: '/dms/dmsBackupApplyRecord/exportDmsBackupScrapRecord',
            //   responseType: 'blob',
            //   data
            // }).then(res => {
            //   if (res.code === 200) {
            //     fileDownload(res, filName + '.xlsx')
            //   } else {
            //     this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
            //   }
            // })
        },
        typeChange(val) {
            this.$emit('changetype', val)
        },
        changePageSize(pageSize) {
            this.pageSize = pageSize;
            this.searchList();
        },
        changePageNum(val) {
            this.pageNum = val;
            this.searchList();
        },
        handleCasChange(val, selectedData) {
            // this.factoryAreaName = selectedData.map(val=>val.label).join('-')
            this.searchParams.useLocation = val[val.length - 1]
            // this.searchParams.orgName = selectedData[selectedData.length-1].label
        },
        handleRangeChange(val) {
            this.searchParams.startTime = val[0]
            this.searchParams.endTime = val[1]
        },
        fiflterLine(dataList) {
            dataList.forEach(val => {
                if (val.children && val.children.length) {
                    const flag = val.children.some(item => item.label.includes('Line'))
                    if (flag) {
                        val.children = val.children.filter(list => !list.label.includes('Line'))
                    }
                    this.fiflterLine(val.children)
                }
            })
            return dataList
        },
        getOrgList() {
            this.axios({
                method: 'get',
                url: '/basic/organization/findListByToken',
                params: {}
            }).then(res => {
                if (res.code === 200) {
                    const obj = {
                        label: 'name',
                        value: 'id',
                        children: 'children'
                    }
                    const dataArr = recursion.convertTree(res.data, obj)
                    this.orgList = this.fiflterLine(dataArr)
                } else {
                    this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
                }
            })
        },
        locationSelectChange(row) {
            this.tablelist.forEach(val => {
                if (val.id === row.id) {
                    val.locationId = row.locationId
                }
            })
        },
        outNumchange(row) {
            this.tablelist.forEach(val => {
                if (val.id === row.id) {
                    val.outNum = Number(row.outNum)
                }
            })
        },
        remarkNumchange(row) {
            this.tablelist.forEach(val => {
                if (val.id === row.id) {
                    val.remark = row.remark
                }
            })
        },
        handleSumit() {
            const data = {
                ...this.paramsInfo,
                applyStatus: 0,
                dmsBackupScrapApplyDetails: [...this.tablelist]
            }
            data.dmsBackupScrapApplyDetails.forEach(val => {
                data.applyNum += Number(val.outNum)
                val.location = val.locationrowList.find(item => item.id === val.locationId).location
                val.shelfName = val.shelvesrowList.find(item => item.id === val.shelfId).shelf
            })
            let url = '/dms/dmsBackupScrapApply/add'
            if (this.$route.query.status === 'edit') {
                data.id = this.$route.query.id
                url = 'dms/dmsBackupScrapApply/edit'
            }
            console.log('提交参数')
            console.log(data)
            this.axios({
                method: 'post',
                url,
                data
            }).then(res => {
                if (res.code == 200) {
                    this.close()
                }
                
            })
        },
        addInfolist() {
            console.log('查询')
            console.log(this.searchParams)
        },
        getApplicationOAList(query) {
            if (query !== '') {
                this.loading = true
                this.axios({
                    method: 'get',
                    url: '/basic/user/searchOAUser',
                    params: {
                        key: query
                    }
                }).then(res => {
                    if (res.code === 200) {
                        this.OAList = res.data.map(item => {
                            return {
                                ...item,
                                showName: item.empno + '----' + item.username
                            }
                        })
                    } else {
                        this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
                    }
                }).finally(() => {
                    this.loading = false
                })
            } else {
                this.OAList = []
            }
        },
        remoteMethod(value) {
            if (this.materielNoList && this.materielNoList.length) {
                return
            }
            this.axios({
                method: 'post',
                url: '/dms/dmsBackupMaterielConfig/queryMaterielNoGoodsNameSpecification',
                data: {value}
            }).then(res => {
                if (res.code === 200) {
                    this.materielNoList = res.data
                } else {
                    this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
                }
            })
        },
        handleMaterielNo(val) {
            this.materielNoStatus = false
            this.clearList()
            if (this.backupNoStatus) {
                return
            }
            if (val) {
                this.materielNoStatus = true
                this.materielNoObj = this.materielNoList.find(item => item.id === val)
                this.backupNoList = this.materielNoObj.dmsBackupStandingBookExts
                this.searchParams = {
                    ...this.searchParams,
                    backupNo: '',
                    assetType: this.materielNoObj.assetType
                }
            } else {
                this.searchParams = {
                    ...this.searchParams,
                    assetType: ''
                }
            }
        },
        clearList() {
            if (!this.searchParams.materielNo && !this.searchParams.backupNo) {
                this.backupNoList = []
                this.materielNoList = []
            }
        },
        remoteMethodBack(value) {
            if (this.backupNoList && this.backupNoList.length) {
                return
            }
            this.axios({
                method: 'post',
                url: '/dms/dmsBackupMaterielConfig/queryBackNoByMaterielNo',
                data: {value}
            }).then(res => {
                if (res.code === 200) {
                    this.backupNoList = res.data
                } else {
                    this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
                }
            })
        },
        handleBackupNo(val) {
            this.backupNoStatus = false
            this.clearList()
            if (this.materielNoStatus) {
                return
            }
            if (val) {
                this.backupNoStatus = true
                this.backupNoObj = this.backupNoList.find(item => item.backuId === val)
                this.materielNoList = this.backupNoObj.dmsBackupMaterielConfigVOs
                this.searchParams = {
                    ...this.searchParams,
                    materielNo: '',
                    assetType: ''
                }
            }
        },
        delRow(row) {
            this.tablelist = this.tablelist.filter(val => val.id !== row.id)
        },
        changeNum() {
            this.pageNum = 1;
            this.searchList();
        },
        searchList() {
            let data = {
                pageNum: this.pageNum,
                pageSize: this.pageSize,
                ...this.searchParams
            }
            for (let key in data) {
                if (!data[key]) {
                    delete data[key]
                }
            }
            this.axios({
                method: 'post',
                url: '/dms/dmsBackupApplyRecord/queryDmsBackupScrapRecordPage',
                data
            }).then(res => {
                if (res.code === 200) {
                    this.tablelist = res.data.list
                    this.tablelist.forEach(val => {
                        val.abcType = val.sparePartsAbc + val.sparePartsVed + '类'
                    })
                    this.total = res.data.total
                } else {
                    this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
                }
            })
        },
        close() {
            this.$router.go(-1)
        },
        companySelectChange(value, row) {
            this.getBackupsByCompany(value, row);
        },
        warehouseSelectChange(value, row) {
            this.getShelfByBackupId(value, row);
        },
        shelvesSelectChange(value, row) {
            this.getLocationByShelfId(value, row);
        },
        companyClear() {
            this.$refs.warehouseSelect.clearSingleSelect();
        },
        warehouseClear() {
            this.$refs.shelvesSelect.clearSingleSelect();
        },
        shelvesClear() {
            this.$refs.locationSelect.clearSingleSelect();
        },
        //公司列表
        getCompanyList(row) {
            return getCompanyList().then(res => {
                if (res.code === 200) {
                    let arr = res.data.map(item => {
                        return {
                            ...item,
                            id: item.id
                        }
                    })
                    if (row) {
                        row.companyrowList = [...arr]
                        this.tablelist.forEach(val => {
                            if (val.id === row.id) {
                                row.companyrowList = [...arr]
                            }
                        })
                    } else {
                        this.companyList = [...this.companyList, ...arr]
                    }
                } else {
                    this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
                }
            })
        },
        getBackupsByCompany(companyId, row) {
            if (!companyId) {
                return;
            }
            let params = {
                companyId: companyId
            }
            if (row) {
                params.companyId = row.companyId
            }
            return getBackupsByCompany(params).then(res => {
                if (res.code === 200) {
                    if (row) {
                        row.warehouserowList = res.data;
                        this.tablelist.forEach(val => {
                            if (val.id === row.id) {
                                row.warehouserowList = res.data;
                            }
                        })
                    } else {
                        this.warehouseList = res.data;
                        this.newwarehouseList = res.data;
                    }
                } else {
                    this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
                }
            })
        },
        getShelfByBackupId(delIds, row) {
            if (!delIds) {
                return;
            }

            let params = {
                delIds: [delIds]
            }
            return getShelfByBackupId(params).then(res => {
                if (res.code === 200) {
                    if (row !== 'old') {
                        this.newshelvesList = res.data
                    } else {
                        this.shelvesList = res.data;
                    }
                } else {
                    this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
                }
            })
        },
        getLocationByShelfId(delIds, row) {
            if (!delIds) {
                return;
            }

            let params = {
                delIds: [delIds]
            }
            return getLocationByShelfId(params).then(res => {
                if (res.code === 200) {
                    if (!(res.data && res.data.length)) {
                        row.locationId = ''
                    }
                    if (row !== 'old') {
                        this.newlocationList = res.data;
                    } else {
                        this.locationList = res.data;
                    }
                } else {
                    this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
                }
            })
        }
    }
}
</script>

<style scoped lang="scss">
.picking {
    height: 100%;
    position: relative;

    .btnList {
        position: absolute;
        bottom: 20px;
        left: 40%;

        .ivu-btn {
            margin: 0 5px;
        }
    }
}

.ivu-card-body {
    padding: 0;
}

.basic-info {
    padding: 20px 5px 5px 5px;
    border-bottom: 1px solid #e8eaec;
    background-color: #fff;

    .basic-info-body {
        margin-bottom: 10px;
    }

    .basic-info-title_bot {
        margin-top: 16px;
    }

    .basic-info-title {
        h2 {
            display: inline-block;
            font-size: 16px;
            padding-left: 10px;
            position: relative;

            &::before {
                content: "";
                position: absolute;
                left: 0;
                top: 0;
                width: 7px;
                height: 24px;
                background: #187bdb;
            }
        }
    }

    .search-form {
        padding: 0;

        .ivu-form-item {
            margin: 0;
        }
    }
}
</style>
